// 1.按照路由模块
// yarn add vue-router
// 2.导入模块
import Vue from "vue";
import VueRouter from "vue-router";
import { getItem } from "../utils/localData";
// 3.注册路由组件 <router-view> <router-link>
Vue.use(VueRouter);
// 4.路由的映射关系
import Login from "../views/Login.vue";
import Register from "../views/Register.vue";
import User from "../views/User.vue";
import UserEdit from "../views/UserEdit.vue";
import Home from "../views/Home.vue";
import Article from "../views/Article.vue";
import UserFollow from "../views/UserFollow.vue";
import UserStar from "../views/UserStar.vue";
import UserComment from "../views/UserComment.vue";
import Comment from "../views/Comment.vue";

const routes = [
  // 不指定跳转到哪个页面组件时，默认跳转到登录页
  { path: "/", redirect: "/home" },
  { path: "/home", component: Home },
  { path: "/login", component: Login },
  { path: "/register", component: Register },
  { path: "/user", component: User },
  { path: "/user_edit", component: UserEdit },
  { path: "/article/:id", component: Article },
  { path: "/user_follow", component: UserFollow },
  { path: "/user_star", component: UserStar },
  { path: "/user_comment", component: UserComment },
  { path: "/comment/:id", component: Comment },
];
// 5.new一个路由实例
const router = new VueRouter({
  routes,
  mode: "history",
});

router.beforeEach((to, from, next) => {
  const pathArr = ["/user", "user_edit"];
  if (pathArr.indexOf(to.path) !== -1) {
    if (getItem()) {
      next();
    } else {
      next({ path: "/login" });
    }
  } else {
    next();
  }
});

// 暴露导出router
export default router;
